package com.soloyogame.anitoys.util;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;


public class SpringTool 
{
	public static ServletContext servletContext;//在系统启动时赋值
	public static Object getBean(HttpServletRequest request,String beanName)
	{
		ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
		Object bean = ctx.getBean(beanName);
		return bean;
	}
	public static <T> T getSpringBean(HttpServletRequest request,String beanName){
		ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
		T bean = (T)ctx.getBean(beanName);
		return bean;
	}
	public static <T> T getSpringBean(String beanName)
	{
		ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		T bean = (T)ctx.getBean(beanName);
		return bean;
	}
	
	public static boolean  containsBean(String beanName){
		ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		return ctx.containsBean(beanName);
	}
	
	public static Object getSpringBeanByXml(String springXmlPath,String beanName){
		 ApplicationContext context = new ClassPathXmlApplicationContext(   
			          new String[] {springXmlPath});   
		  BeanFactory factory = (BeanFactory) context;   
		  
		  Object bean=factory.getBean(beanName);  
		  return bean;
	}
	public static Object getSpringBeanByXml(String[] xmlPath,String beanName){
		 ApplicationContext context = new ClassPathXmlApplicationContext(xmlPath);   
		  BeanFactory factory = (BeanFactory) context;   
		  
		  Object bean=factory.getBean(beanName);  
		  return bean;
	}
	public static <T>T getBeanByXml(String springXmlPath,String beanName){
		 ApplicationContext context = new ClassPathXmlApplicationContext(   
			          new String[] {springXmlPath});   
		  BeanFactory factory = (BeanFactory) context;   
		  
		  T bean=(T)factory.getBean(beanName);  
		  return bean;
	}
	
	public static ServletContext getServletContext() 
	{
		return servletContext;
	}
	public static void setServletContext(ServletContext servletContext) {
		SpringTool.servletContext = servletContext;
	}

}
